package com.yang.spring.dao;/**
 * Created by CoolWen on 2017/10/26.
 */


import com.yang.spring.model.User;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CoolWen
 * @version 2017-10-26 9:34
 */
@Repository("jdbcUserDao")
public class UserDao implements IUserDao {

    private JdbcTemplate jdbcTemplate;


    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void add(User user) {
        this.jdbcTemplate.update(
                "insert into users (username, password,nickname) values (?,?,?)",
                user.getUsername(), user.getPassword(), user.getNickname());

    }

    @Override
    public void update(User user) {
        this.jdbcTemplate.update(
                "update users set username = ?,password=?,nickname=?  where id = ?",
                user.getUsername(), user.getPassword(), user.getNickname(), user.getId());

    }

    @Override
    public void delete(int id) {
        this.jdbcTemplate.update("delete from users where id = ?", id);
    }

    @Override
    public Map<String, Object> load(int id) {
        Map<String, Object> map=new HashMap<String, Object>();
        Object[] params = new Object[] {id};
        return this.jdbcTemplate.queryForObject("select * from users where id=?",params,new ColumnMapRowMapper());
    }

    @Override
    public List<Map<String, Object>> list() {

        return  this.jdbcTemplate.query("select * from users",new ColumnMapRowMapper());
    }


}
